<template>
  <el-dialog :visible.sync="visible" :title="title"
             @closed='closedDialog'>
    <KAudioField :field="field"
                 :fieldIndex="field.index"
                 :uploadPath="audioUploadPath"
                 @upload="handleAudioUpload"
                 @del="deleteAudio"/>
    <span class="dialog-footer" slot="footer">
        <el-button @click="closedDialog">取 消</el-button>
        <el-button @click="commit" type="primary">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import KImgField from "../knowledge/knowledgeEdit/KImgField";
  import KAudioField from "../knowledge/knowledgeEdit/KAudioField";

  export default {
    name: "importAudioDialog",
    components: {
      KImgField,
      KAudioField
    },
    props: {
      audioUploadPath: {
        type: String,
        default: ''
      },
    },
    data() {
      return {
        title: '上传音频',
        visible: false,
        field: {
          index: 0,
          fieldValue: {
            type: '',
            title: '',
            paths: []
          }
        }
      }
    },
    methods: {
      handleAudioUpload(fieldIndex, audioPath) {
        this.field.fieldValue.paths.push(audioPath)
      },
      deleteAudio(fieldIndex, audioIndex) {
        this.field.fieldValue.paths.splice(audioIndex, 1)
      },
      commit: function () {
        if (this.field.fieldValue.paths.length) {
          let param = new URLSearchParams();
          param.append("fieldValue", JSON.stringify(this.field.fieldValue))
          this.axios.post('/pmph/action/kindEditor/parseKnowledgeFieldAudioType', param)
            .then((response) => {
              this.$parent.editor.afterFocus()
              // 如果是修改, 则清理之前的图片和图题图注;
              if (this.title == '修改音频') {
                let audioEl = KindEditor(this.$parent.editor.cmd.sel.focusNode).parent().first()
                var cnt_doc = this.$parent.editor.cmd.doc
                // 删除原音频标题
                if (cnt_doc.getElementById('v_title_' + audioEl.attr("id"))) {
                  cnt_doc.getElementById('v_title_' + audioEl.attr("id")).remove()
                }
                audioEl.parent().html(response.data.html).remove(true)
              } else {
                this.$parent.editor.insertHtml(response.data.html + "<p>请继续编辑内容...</p>")
              }
              this.$parent.editor.afterBlur()
              this.closedDialog()
            })
        }
      },
      closedDialog() {
        this.title = '上传音频'
        this.field.fieldValue.paths = []
        this.field.fieldValue.type = ''
        this.field.fieldValue.title = ''
        this.visible = false
      }
    }
  }
</script>

<style scoped>

</style>
